<?php
namespace app\api\model;


use think\Model;
use think\Db;
use redis\Redis;
use think\facade\Request;
class Cart extends Model
{


    private $basket      = [];     //私有空数组用于存放商品信息
    // private $cachekey    = Null;
    private $expire      = 43200;  //redis购物车商品缓存过期时间
   //  function __construct()
   // {
   //     //如果成员属性没有声明，默认就是公有属性
   //    $redis = new \Redis();
   //    $redis->connect('127.0.0.1',6379);
   // }

    function __construct(){
       $uid = Request::param('uid');
 
        $this->redis_ext    = '.'.'redis';      //redis缓存键名拼接项目中文名称字符串
        $this->cachekey     = 'user.cart'.$uid.$this->redis_ext;  //redis缓存键名拼接用户ID与项目中文名称字符串为对象用户购物车缓存键名
        $this->basket       = json_decode(redis()->get($this->cachekey),true);     //获取对象用户的redis购物车商品缓存信息并解码为PHP数组
    }
    public function addToCart($data){
    
       //判断对象商品是否已经存在redis购物车商品缓存内
        if( $this->isExist($data['id'],$data['attr_id']) ){
            //存在时增加该对象商品数量
            return $this->add($data);
        }
        
        //对象商品不在redis购物车商品缓存内时
        $tmp  = [];
        $tmp['id']            = $data['id'];        //对象商品ID
        $tmp['attr_id']          = $data['attr_id'];   //对象商品对应属性ID
        $tmp['attr_value']          = $data['attr_value']; //对象商品对应属性名称
        $tmp['goods_attr'] = $data['attr_id'];
        $tmp['num']        = $data['num'];   //对象商品数量,新增的商品默认加入数量为1
        $tmp['amount']         = $data['amount'];     //对象商品对应属性单价
        $tmp['goods_price'] = $data['goods_price'];
        $tmp['attr'] = $data['spec'];
          
        $this->basket[] = $tmp;        //新的商品信息存入redis购物车商品缓存信息解码的PHP数组内，每件属性商品信息对应一个索引键值
    
        //重新将新的购物车商品信息数组编码为json字符串存入对象用户redis购物车商品缓存内
        redis()->setex($this->cachekey,$this->expire,json_encode($this->basket));

        return_json(200,'成功',true);
    
    }

     public function isExist($id,$attr_id){
        $isExist = false;
        
        //当对象用户redis购物车商品缓存不为空时
        if( !empty($this->basket) ){

            foreach ($this->basket as $key=>$val){

                if( $val['id'] == $id && $attr_id == $val['attr_id'] ){

                    $isExist = true;
                    break;
                }
            }
        }
        return $isExist;
    }


    //  public function addbasket( $data ){
       
    // }



    /*添加商品
    * @param $id商品id
    * @param $number 添加的数量 默认为1
    * @param $type 1为在原有商品数上添加 总商品数= 当前数 + 历史数，2为总商品数 默认为 1
    */
    public function add($data){
        
        $goods_number = 0;  //加入不成功时默认返回添加数量为0
        //商品ID不为空并且商品在redis购物车商品缓存内
        if( !empty($data['id']) && $this->isExist($data['id'] ,$data['attr_id']) ){
            $cache_detail = $this->basket;  //获取用户购物车所有商品信息
            foreach ($cache_detail as $key=>$val){
                if( $val['id'] == $data['id'] && $val['attr_id'] == $data['attr_id']){
                    $val['num'] = $val['num']+$data['num'];     //购物车存在该商品时增加该商品数量
               

                    $this->basket[$key] = $val;                              //购物车存在该商品时重新将新的商品信息放入该商品的redis缓存信息内（$key即为该商品的redis缓存键值）
                    redis()->setex($this->cachekey,$this->expire,json_encode($this->basket)); //购物车存在该商品时更新该商品的redis缓存信息
                    $goods_number = $val['num'];                    //商品加入成功将商品数量赋值变量返回
                    break;
                }
            }
        }
        return_json(200,'成功',true);
    }


    //获取所有商品信息
    public function getAll(){
        $res =  $this->basket;
        //判断是否为空
        if(!empty($res)){
            foreach ($res as $k => $v) {
            $v += db('goods')->field('goods_title,title_thumb')->where('id',$v['id'])->find();
          $res[$k]=$v;
        }
        }
        
       return_json(200,'成功',$res);
      
    }


     // 编辑某商品数量
    public function edit($data)
    {//+ - 填写


        $data['attrid'] = json_decode($data['attrid']);


        if (!empty($data['id']) && $this->isExist($data['id'], $data['attrid'])) {
            $cache_detail = $this->basket;
            foreach ($cache_detail as $key => $val) {
                if ($val['id'] == $data['id'] && $val['attr_id'] == $data['attrid']) {

                    if(isset($data['operation']) && !empty($data['operation'])){
                      $val['num'] = $val['num'] + $data['operation'];
                     if( $val['num'] <= 0 ){
                        $this->dele($data['id'] ,$data['attrid']);

                        redis()->setex($this->cachekey,$this->expire,json_encode($this->basket));
                        // $val['num'] = 0;
                        break;
                    }
                    }elseif(isset($data['type']) && !empty($data['type']) &&$data['num']>0){
                        $val['num'] = $data['num'];
                    }
                                        
                    $this->basket[$key] = $val;
                    redis()->setex($this->cachekey, $this->expire, json_encode($this->basket));

                }
            }
            return_json(200,'成功',true); 
        }
    }

    public function updateAttr($data){//修改属性

        $data['battr'] = json_decode($data['battr']);
        $data['spec'] = json_decode($data['spec']);
        $data['attr'] = json_decode($data['attr']);

        if(!empty($data['id']) && $this->isExist($data['id'],$data['battr']) && $data['num']>0){
            $cache_detail = $this->basket;
            //查看修改的属性是否存在，在的话更改数量，不在增加
            if($this->isExist($data['id'],$data['attr'])){
               
             foreach ($cache_detail as $key=>$val){

                if( $val['id'] == $data['id'] && $data['battr'] == $val['attr_id'] ){
                    unset($this->basket[$key]);
             
                }
                // if( $val['id'] == $data['id'] && $data['attr'] == $val['attr_id'] ){
                //    $val['num'] = $val['num']+$data['num'];
                //   $this->basket[$key] = $val;

                // }
            }
              foreach ($cache_detail as $key=>$val){

              
                if( $val['id'] == $data['id'] && $data['attr'] == $val['attr_id'] ){
                   $val['num'] = $val['num']+$data['num'];
                  $this->basket[$key] = $val;
                  
                }
            }
            }else{
      
            foreach ($cache_detail as $key => $val) {
                if ($val['id'] == $data['id'] && $val['attr_id'] == $data['battr']) {
                    $val['attr_value'] = $data['name'];
                    $val['attr'] = $data['spec'];
                    $val['goods_attr'] = $data['attr'];
                    $val['attr_id']  = $data['attr'];
                    $val['amount'] = $data['price'];    
                  $this->basket[$key] = $val;
                }
            } 
            }
           
             redis()->setex($this->cachekey, $this->expire, json_encode($this->basket));
             return_json(200,'成功',true);
        }

    }


    //删除商品
    public function dele($ids){
        if(is_array($ids)){
            foreach ($ids as $v){
                foreach ($this->basket as $k=>$val) {
                    if( $val['id'] == $v['id'] && $val['attrid'] == $v['attrid'] ){
                        array_splice($this->basket,$k,1);
                    }
                }
            }
        }else{
            foreach ($this->basket as $k=>$val) {
                if( $val['id'] == $ids){
                    //unset(self::$basket[$k]);
                    array_splice($this->basket,$k,1);
                }
            }
        }
        redis()->setex($this->cachekey,$this->expire,json_encode($this->basket));
        return true;
    }




   




}

